package exchange

import (
	"global/libs/structs"
	"github.com/parnurzeal/gorequest"
	"github.com/ngaut/log"
	"encoding/json"
	"global/core"
	"strings"
	"fmt"
	"global/libs/exchanges"
	"time"
	"global/model"
)

type bitZSymbolDatas struct {
	Id 			string 		`json:"id"`
	CoinFrom 	string 		`json:"coinFrom"`
	CoinTo 		string 		`json:"coinTo"`
	NumberFloat string 		`json:"numberFloat"`
	PriceFloat 	string 		`json:"priceFloat"`
	Status 		string 		`json:"status"`
	MinTrade 	string 		`json:"minTrade"`
	MaxTrade 	string 		`json:"maxTrade"`
}

type BitZSymbol struct {
	Client 		*gorequest.SuperAgent
	Ctx 		*core.Context
	exchange 	*model.Exchange
	ticker 		*time.Ticker
	coins 		map[string]int
}

func NewBitZSymbol(ctx *core.Context, coins map[string]int, exchange *model.Exchange) SymbolInterface {
	return &BitZSymbol{
		Ctx: 		ctx,
		Client: 	gorequest.New(),
		exchange: 	exchange,
		ticker: 	time.NewTicker(1 * time.Minute),
		coins: 		coins,
	}
}

func (s *BitZSymbol) Start()  {
	go func() {
		s.handle()
		for t := range s.ticker.C {
			_ = t
			s.handle()
		}
	}()
}

func (s *BitZSymbol) handle()  {
	symbols, err := s.requestSymbol()
	if err != nil {
		log.Errorf("Error: %s", err.Error())
		return
	}

	if len(symbols) == 0 { return }

	// 从数据库中获取
	dbSymbols, err := model.ExchangePairModel.Find(s.exchange.Mid)
	if err != nil {
		log.Errorf("Error: %s", err)
		return
	}

	add, del := compare(symbols, dbSymbols)

	conn := s.Ctx.GetBaseRedis().Get()
	defer conn.Close()

	addPairs(add, conn, s.exchange, s.coins)
	delPairs(del, conn, s.exchange)
}

// 请求 Symbol 数据
func (s *BitZSymbol) requestSymbol() (map[string]*structs.Symbol, error) {
	_, body, errs := s.Client.
		Get(core.GetBitZUrl("symbolList")).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36").
		End()
	if len(errs) > 0 {
		log.Errorf("Error: %s", errs[0])
		return nil, errs[0]
	}

	type responseData struct {
		exchanges.BitzBaseResponse
		Data        map[string]bitZSymbolDatas		`json:"data"`
	}

	var response responseData
	err := json.Unmarshal([]byte(body), &response)
	if err != nil {
		log.Errorf("Error: %s", err)
		return nil, err
	}

	symbols := make(map[string]*structs.Symbol)
	for _, v := range response.Data {
		from := strings.ToLower(v.CoinFrom)
		to := strings.ToLower(v.CoinTo)
		key := fmt.Sprintf("%s_%s", from, to)
		symbols[key] = &structs.Symbol{
			From: 		from,
			To: 	 	to,
		}
	}
	return symbols, nil
}

